package com.clx.job;

import com.clx.constants.SystemConstants;
import com.clx.domain.entity.Article;
import com.clx.service.ArticleService;
import com.clx.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class UpdateViewCountJob {

    @Autowired
    RedisCache redisCache;
    @Autowired
    ArticleService articleService;

    @Scheduled(cron = "* 0/10 * * * ?")
    public void updateViewCount() {
        // 获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap(SystemConstants.REDIS_BLOG_ARTICLE_VIEW_COUNT);
        // 更新到数据库中

        List<Article> articles = viewCountMap.entrySet().stream().map(
                entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue())).collect(Collectors.toList());
        articleService.updateBatchById(articles);
    }
}
